package toy.keli.eshi

import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.OpenableColumns
import androidx.core.content.FileProvider
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.ByteArrayOutputStream
import java.io.InputStream


class MainActivity : FlutterActivity() {
  
     private val CHANNEL = "app/file_provider" // 与Flutter侧一致

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            when(call.method) {
                "get_content_uri" -> {
                    val filePath = call.argument<String>("file_path") // Flutter传入的文件路径
                    val contentUri = getContentUri(this, filePath)
                    if (contentUri != null) {
                        result.success(contentUri.toString())
                    } else {
                        result.error("ERROR", "生成 content://路径失败", null)
                    }
                }

                "openFile" -> {
                    val curi = getContentUri(this, call.argument("path"))
                    if (curi == null) {
                        result.error("ERROR", "生成content://路径失败", null)
                    } else {
                        val uri = Uri.parse(curi.toString())
                        //                val uri: Uri = Uri.parse(call.argument("uri"))
                        val intent: Intent = Intent(Intent.ACTION_VIEW)
                        intent.setDataAndType(uri, context.getContentResolver().getType(uri))
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        this.startActivity(intent)
                        result.success("Opened URI")
                    }
                }

                "getContentUriData" -> {
                    val uriString = call.argument<String>("uri")
                    if (uriString != null) {
                        val uri = Uri.parse(uriString)
                        try {
                            // 获取文件数据
                            val fileData = readUriToBytes(uri)
                            // 获取MIME类型
                            val mimeType = contentResolver.getType(uri)
                            // 获取文件名
                            val fileName = getFileName(uri)

                            // 返回结果给Dart
                            result.success(
                                mapOf(
                                    "data" to fileData,
                                    "mimeType" to mimeType,
                                    "fileName" to fileName
                                )
                            )
                        } catch (e: Exception) {
                            result.error("READ_FAILED", "无法读取文件内容: ${e.message}", null)
                        }
                    }
                }

                else -> {
                    result.notImplemented()
                }
            }
        }

        // 监听外部应用打开文件的事件（示例：获取文件路径并通知Dart）
        handleIntent()
    }
    // 当应用从后台被唤醒时，再次处理Intent
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        handleIntent()
    }
    // 核心方法：将文件路径转为content:// URI
    private fun getContentUri(context: Context, filePath: String?): Uri? {
        if (filePath == null) return null
        val file = java.io.File(filePath)
        return try {
            FileProvider.getUriForFile(
                context,
                "${context.packageName}.fileprovider", // 与Manifest中authorities一致
                file
            )
        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
            null
        }
    }

    // 处理外部应用传递的Intent（如文件打开事件）
    private fun handleIntent() {
        val intent = intent
        val action = intent.action
        val type = intent.type

        // 判断是否是"打开文件"的事件
        if (Intent.ACTION_VIEW == action && type != null) {
            // 获取文件的URI（可能是content://或file://格式）
            val uri = intent.data
            uri?.let {
                // 将URI转换为字符串，通过MethodChannel发送给Dart
                val channel = MethodChannel(flutterEngine?.dartExecutor?.binaryMessenger!!, CHANNEL)
                channel.invokeMethod("onFileOpened", it.toString())
            }
        }
    }

    // 读取URI对应的文件为字节数组
    private fun readUriToBytes(uri: Uri): ByteArray {
        val inputStream: InputStream? = contentResolver.openInputStream(uri)
        val outputStream = ByteArrayOutputStream()
        val buffer = ByteArray(4096)
        var bytesRead: Int

        try {
            if (inputStream == null) {
                throw Exception("无法打开输入流")
            }

            while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                outputStream.write(buffer, 0, bytesRead)
            }
            return outputStream.toByteArray()
        } finally {
            inputStream?.close()
            outputStream.close()
        }
    }

    // 获取URI对应的文件名
    private fun getFileName(uri: Uri): String? {
        var fileName: String? = null
        if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
            val cursor = contentResolver.query(uri, null, null, null, null)
            cursor?.use {
                if (it.moveToFirst()) {
                    val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                    if (nameIndex != -1) {
                        fileName = it.getString(nameIndex)
                    }
                }
            }
        }
        return fileName
    }
      // private val CHANNEL = "keyboard_detector"
    // private val TAG = "PhysicalKeyboardCheck"

    // override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
    //     super.configureFlutterEngine(flutterEngine)

    //     MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
    //         when (call.method) {
    //             "hasPhysicalKeyboard" -> {
    //                 val hasKeyboard = checkPhysicalKeyboard()
    //                 Log.d(TAG, "外接键盘检测结果: $hasKeyboard")
    //                 result.success(hasKeyboard)
    //             }
    //             else -> result.notImplemented()
    //         }
    //     }
    // }

    // /**
    //  * 检测是否存在外接物理键盘
    //  * @return true: 存在外接键盘; false: 不存在
    //  */
    // private fun checkPhysicalKeyboard(): Boolean {
    //     // 1. 获取所有输入设备ID
    //     val deviceIds = InputDevice.getDeviceIds()

    //     // 2. 遍历所有输入设备
    //     for (deviceId in deviceIds) {
    //         val device = InputDevice.getDevice(deviceId)
    //         device?.let {
    //             // 3. 过滤条件：
    //             //    - 是外部设备（isExternal为true）
    //             //    - 具备键盘输入源（支持按键输入）
    //             //    - 不是虚拟键盘（排除系统软键盘）
    //             if (it.isExternal &&
    //                 it.sources and SOURCE_KEYBOARD == SOURCE_KEYBOARD &&
    //                 !isVirtualKeyboard(it, applicationContext)) {
    //                 return true
    //             }
    //         }
    //     }
    //     return false
    // }

    // /**
    //  * 判断是否为虚拟键盘（如系统软键盘、屏幕键盘）
    //  */
    // private fun isVirtualKeyboard(device: InputDevice, context: Context): Boolean {
    //     // 虚拟键盘通常没有物理设备ID，或制造商为系统厂商
    //     return device.productId == 0 && device.vendorId == 0
    //             || device.name?.contains("Virtual", ignoreCase = true) == true
    //             || device.name?.contains("软键盘", ignoreCase = true) == true
    // }

}
